import { getToken, setToken, removeToken } from '@/utils/auth'
import { loginApi, getInfoApi, updatePasswordApi } from '@/api/user'

const state = {
  // 获取token
  token: getToken(),
  // 用户信息
  userInfo: {}
}
const mutations = {
  setToken(state, token) {
    state.token = token
    // 保存到cookie持久化
    setToken(token)
  },
  // 用户信息
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  // 处理token过期信息
  removeToken(state) {
    state.token = null
    removeToken()
  },
  // 清除用户信息
  removeUserInfo(state) {
    state.userInfo = {}
  }
}

const actions = {
  // 把两个mutation合并到一起
  logout({ commit }) {
    commit('removeToken')
    commit('removeUserInfo')
  },
  // 登录
  async login({ commit }, data) {
    const token = await loginApi(data)
    console.log(token)
    commit('setToken', token)
  },
  // 获取用户信息
  async getUserInfo(context) {
    // setTimeout(() => {
    // context.commit('setUserInfo', { name: '张三' })
    // }, 3000)
    const res = await getInfoApi()
    context.commit('setUserInfo', res)
  },
  // // 修改密码
  async updatePassword({ commit }, data) {
    await updatePasswordApi(data)
  }

}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
